package org.example.managere.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 */
public class ExcelExportUtil {

    /**
     * 生成Excel文件
     *
     * @param headers 表头
     * @param data 数据列表
     * @param sheetName 工作表名称
     * @return Excel文件字节数组
     * @throws IOException 如果写入过程中发生IO错误
     */
    public static <T> byte[] exportToExcel(Map<String, String> headers, List<T> data, String sheetName) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);
            
            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 创建表头行
            Row headerRow = sheet.createRow(0);
            int columnIndex = 0;
            for (String field : headers.keySet()) {
                Cell cell = headerRow.createCell(columnIndex++);
                cell.setCellValue(headers.get(field));
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            int rowIndex = 1;
            for (T item : data) {
                Row row = sheet.createRow(rowIndex++);
                fillDataRow(row, item, headers.keySet().toArray(new String[0]));
            }
            
            // 调整列宽
            for (int i = 0; i < headers.size(); i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
    
    /**
     * 填充数据行
     *
     * @param row 行对象
     * @param data 数据对象
     * @param fields 字段名数组
     */
    private static <T> void fillDataRow(Row row, T data, String[] fields) {
        try {
            int columnIndex = 0;
            for (String fieldName : fields) {
                Cell cell = row.createCell(columnIndex++);
                Field field = findField(data.getClass(), fieldName);
                if (field != null) {
                    field.setAccessible(true);
                    Object value = field.get(data);
                    setCellValue(cell, value);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("导出数据时出错: " + e.getMessage(), e);
        }
    }
    
    /**
     * 递归查找字段（支持嵌套字段）
     *
     * @param type 类类型
     * @param fieldName 字段名
     * @return 找到的字段
     */
    private static Field findField(Class<?> type, String fieldName) {
        if (fieldName.contains(".")) {
            String[] parts = fieldName.split("\\.", 2);
            try {
                Field field = type.getDeclaredField(parts[0]);
                field.setAccessible(true);
                return findField(field.getType(), parts[1]);
            } catch (NoSuchFieldException e) {
                return null;
            }
        } else {
            try {
                return type.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // 检查父类
                if (type.getSuperclass() != null) {
                    return findField(type.getSuperclass(), fieldName);
                }
                return null;
            }
        }
    }
    
    /**
     * 根据值类型设置单元格值
     *
     * @param cell 单元格
     * @param value 值对象
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Float) {
            cell.setCellValue((Float) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof Date) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            cell.setCellValue(dateFormat.format((Date) value));
        } else {
            cell.setCellValue(value.toString());
        }
    }
} 